package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.decoration.UserMammonCongratulate;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserMammonCongratulateDaoImpl extends TempDataObjectDao<UserMammonCongratulate> {

    public Map<String, UserMammonCongratulate> getUserMammonCongratulateMap(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<String, UserMammonCongratulate> dataMap = new ConcurrentHashMap<>();
        String sql = "select * from t_u_mammon_congratulate where userId=? order by congratulateTime desc";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserMammonCongratulate data = parse(rs);
                dataMap.put(data.getRecordUid(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    @Override
    protected boolean addData(UserMammonCongratulate data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_mammon_congratulate(userId,recordUid,congratulateTime) values (?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getUserId());
            call.setString(i++, data.getRecordUid());
            call.setLong(i++, data.getCongratulateTime());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(UserMammonCongratulate data) {
        return false;
    }

    @Override
    protected UserMammonCongratulate parseData(ResultSet rs) throws SQLException {
        UserMammonCongratulate data = new UserMammonCongratulate();
        data.setUserId(rs.getLong("userId"));
        data.setRecordUid(rs.getString("recordUid"));
        data.setCongratulateTime(rs.getLong("congratulateTime"));
        return data;
    }
}
